package cn.chiship.framework.third.biz.all.service.impl;

import cn.chiship.framework.third.biz.all.entity.MemberUserBind;
import cn.chiship.framework.third.biz.all.entity.MemberUserBindExample;
import cn.chiship.framework.third.biz.all.service.MemberUserBindService;
import cn.chiship.framework.third.biz.wxmini.pojo.dto.AppletRegistrationDto;
import cn.chiship.framework.third.core.common.ThirdApplicationOauthTypeEnum;
import cn.chiship.sdk.cache.service.UserCacheService;
import cn.chiship.sdk.cache.util.JwtUtil;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.enums.UserTypeEnum;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.all.mapper.MemberUserMapper;
import cn.chiship.framework.third.biz.all.entity.MemberUser;
import cn.chiship.framework.third.biz.all.entity.MemberUserExample;
import cn.chiship.framework.third.biz.all.service.MemberUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 会员业务接口实现层
 * 2022/2/23
 *
 * @author lijian
 */
@Service
public class MemberUserServiceImpl extends BaseServiceImpl<MemberUser, MemberUserExample> implements MemberUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MemberUserServiceImpl.class);

    @Resource
    MemberUserMapper memberUserMapper;
    @Resource
    MemberUserBindService memberUserBindService;
    @Resource
    UserCacheService userCacheService;

    /**
     * 小程序登录
     *
     * @param appletRegistrationDto
     * @param ip
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult appletLogin(AppletRegistrationDto appletRegistrationDto, String ip) {
        return doThirdApplicationLogin(
                appletRegistrationDto.getOpenId(),
                appletRegistrationDto.getMobile(),
                appletRegistrationDto.getAvatar(),
                appletRegistrationDto.getNickName(),
                appletRegistrationDto.getGender(),
                ip,
                ThirdApplicationOauthTypeEnum.APPLICATION_OAUTH_WX_MINI
        );
    }

    public BaseResult doThirdApplicationLogin(
            String oathId,
            String mobile,
            String avatar,
            String nickName,
            Byte gender,
            String loginIp,
            ThirdApplicationOauthTypeEnum thirdApplicationOauthTypeEnum) {
        MemberUserBindExample memberUserBindExample = new MemberUserBindExample();
        memberUserBindExample.createCriteria().andBindKeyEqualTo(thirdApplicationOauthTypeEnum.getType());
        List<MemberUserBind> memberUserBinds = memberUserBindService.selectByExample(memberUserBindExample);
        /**
         * 根据手机号查找用户
         */
        MemberUserExample memberUserExample = new MemberUserExample();
        memberUserExample.createCriteria().andMobileEqualTo(mobile);
        List<MemberUser> memberUsers = memberUserMapper.selectByExample(memberUserExample);
        MemberUser memberUser = null;
        if (memberUsers.isEmpty()) {
            /**
             * 判断三方授权码是否存在，若存在，提示已经注册
             */
            if (!memberUserBinds.isEmpty()) {
                return BaseResult.error("该授权码已绑定其他账号，但与手机号不匹配");
            }
            /**
             * 不存在则注册
             */
            MemberUser user = new MemberUser();
            user.setAvatar(avatar);
            user.setMobile(mobile);
            user.setNickName(nickName);
            user.setGender(gender);
            super.insertSelective(user);

            memberUser = user;
        } else {
            memberUser = memberUsers.get(0);
        }
        if (memberUserBinds.isEmpty()) {
            MemberUserBind memberUserBind = new MemberUserBind();
            memberUserBind.setUserId(memberUser.getId());
            memberUserBind.setBindAvatar(avatar);
            memberUserBind.setBindNickName(nickName);
            memberUserBind.setBindKey(ThirdApplicationOauthTypeEnum.APPLICATION_OAUTH_WX_MINI.getType());
            memberUserBind.setBindValue(oathId);
            memberUserBind.setBindTime(System.currentTimeMillis());
            memberUserBindService.insertSelective(memberUserBind);
        }
        memberUser.setLastLoginIp(loginIp);
        memberUser.setLastLoginTime(System.currentTimeMillis());
        super.updateByPrimaryKeySelective(memberUser);
        CacheUserVO userVO = new CacheUserVO(UserTypeEnum.MEMBER);
        userVO.setMobile(memberUser.getMobile());
        userVO.setUsername(memberUser.getUserName());
        userVO.setId(memberUser.getId());
        userVO.setRealName(memberUser.getRealName());
        userVO.setAvatar(memberUser.getAvatar());
        String accessToken = JwtUtil.createToken(userVO);
        userCacheService.cacheUser(accessToken, userVO);
        return BaseResult.ok(accessToken);
    }
}
